import asyncio
from threading import Thread

import websockets
import user_data
import random

async def func():
    pass

# 向服务器端认证，用户名密码通过才能退出循环
async def auth_system(websocket):
    while True:
        cred_text = '{}:{}'.format(user_data.username,user_data.password)
        await websocket.send(cred_text)
        response_str = await websocket.recv()
        print(response_str)
        if "congratulation" in response_str:
            return True

# 向服务器端发送认证后的消息
async def send_msg(websocket):
    while True:
        # _text = input("please enter your context: ")
        _text = 'rtsp://cameraId={}&personId={}&img=base64图片格式{}'.format(random.randint(1,100),random.randint(1,100),random.randint(1,100))
        #_text暂时写死，向服务端发送的数据
        if _text == "exit":
            print(f'you have enter "exit", goodbye')
            await websocket.close(reason="user exit")
            return False
        await websocket.send(_text)
        print('发送包：'+_text)
        while True:
            recv_text = await websocket.recv()
            # await asyncio.sleep(1)
            print(f"接收：{recv_text}")
            if recv_text  == 'data end':
                break
        await asyncio.sleep(10)

# 客户端主逻辑
async def main_logic():
    async with websockets.connect('ws://127.0.0.1:5678') as websocket:
        await auth_system(websocket)

        await send_msg(websocket)

def start_loop(loop,client_):
    asyncio.set_event_loop(loop)
    loop.run_until_complete(client_)
    loop.run_forever()

# asyncio.get_event_loop().run_until_complete()
def run():
    # 主线程中创建一个 new_loop
    new_loop = asyncio.get_event_loop()
    # 创建子线程 在其中开启无限事件循环
    t = Thread(target=start_loop, args=(new_loop,main_logic()))
    t.start()
    asyncio.run_coroutine_threadsafe(func(),new_loop)

if __name__ == '__main__':
    run()